<template>
  <div class="shop-list">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="店铺名称">
          <el-input v-model="searchForm.name" placeholder="请输入店铺名称" clearable />
        </el-form-item>
        <el-form-item label="店铺状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="营业中" :value="1" />
            <el-option label="已关闭" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="营业时间">
          <el-time-picker
            v-model="searchForm.openTime"
            placeholder="开始时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 120px"
          />
          <span class="separator">-</span>
          <el-time-picker
            v-model="searchForm.closeTime"
            placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">添加店铺</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="shopList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" width="50" />
      <el-table-column prop="name" label="店铺名称" min-width="180">
        <template #default="{ row }">
          <div class="shop-info">
            <el-image
              :src="row.image"
              :preview-src-list="[row.image]"
              fit="cover"
              class="shop-logo"
            />
            <div class="shop-detail">
              <span class="shop-name">{{ row.name }}</span>
              <span class="shop-address">{{ row.area }}{{ row.address }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="openHours" label="营业时间" width="160">
        <template #default="{ row }">
          {{ row.openHours }}
        </template>
      </el-table-column>
      <el-table-column prop="averagePrice" label="均价" width="100">
        <template #default="{ row }">
          ¥{{ formatNumber(row.averagePrice) }}
        </template>
      </el-table-column>
      <el-table-column prop="sold" label="销量" width="100" />
      <el-table-column prop="comments" label="评论数" width="100" />
      <el-table-column prop="score" label="评分" width="80" />
      <el-table-column prop="phone" label="联系电话" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '营业中' : '已关闭' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button 
            type="primary" 
            link 
            @click="handleStatusChange(row)"
          >
            {{ row.status === 1 ? '关闭' : '开启' }}
          </el-button>
          <el-button type="primary" link @click="handleViewGoods(row)">查看商品</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllShopList, deleteShop, updateShop } from '@/api/shop'
import service from '@/utils/request'

const router = useRouter()
const loading = ref(false)
const shopList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = ref({
  name: '',
  status: '',
  openTime: '',
  closeTime: ''
})

// 获取店铺列表
const getShopList = async () => {
  loading.value = true
  try {
    const res = await getAllShopList(currentPage.value, pageSize.value)
    shopList.value = res
    total.value = res.length
  } catch (error) {
    console.error('获取店铺列表失败：', error)
    ElMessage.error('获取店铺列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getShopList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    status: '',
    openTime: '',
    closeTime: ''
  }
  handleSearch()
}

// 添加店铺
const handleAdd = () => {
  router.push('/jiang/shop/add')
}

// 编辑店铺
const handleEdit = (row) => {
  router.push(`/jiang/shop/edit/${row.id}`)
}

// 查看店铺商品
const handleViewGoods = (row) => {
  router.push({
    path: '/jiang/goods',
    query: { shopId: row.id }
  })
}

// 修改店铺状态
const handleStatusChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '关闭' : '开启'}该店铺吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await updateShop({
      ...row,
      status: row.status === 1 ? 0 : 1
    })
    
    ElMessage.success('操作成功')
    getShopList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改店铺状态失败：', error)
      ElMessage.error('操作失败')
    }
  }
}

// 删除店铺
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该店铺吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteShop(parseInt(row.id))
    
    ElMessage.success('删除成功')
    getShopList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除店铺失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getShopList()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getShopList()
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化数字
const formatNumber = (num) => {
  const n = Number(num)
  if (isNaN(n)) return '0.00'
  return n.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

onMounted(() => {
  getShopList()
})
</script>

<style lang="scss" scoped>
.shop-list {
  .operation-area {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .search-form {
      flex: 1;

      .separator {
        margin: 0 8px;
        color: #909399;
      }
    }

    .operation-buttons {
      margin-left: 20px;
    }
  }

  .shop-info {
    display: flex;
    align-items: center;
    gap: 12px;

    .shop-logo {
      width: 50px;
      height: 50px;
      border-radius: 4px;
    }

    .shop-detail {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .shop-name {
        font-weight: 500;
      }

      .shop-address {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .pagination-area {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
